package com.kclm.xsap.web.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kclm.xsap.entity.CourseCardEntity;
import com.kclm.xsap.entity.CourseEntity;
import com.kclm.xsap.entity.ScheduleRecordEntity;
import com.kclm.xsap.service.CourseCardService;
import com.kclm.xsap.service.CourseService;
import com.kclm.xsap.service.ScheduleRecordService;
import com.kclm.xsap.utils.R;
import com.kclm.xsap.vo.CourseLimitVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 课程管理控制器
 */
@Slf4j
@Controller
@RequestMapping("/course")
public class CourseController {
    private static String IGNORE = "version";
    @Autowired
    private CourseService courseService;
    @Autowired
    private CourseCardService courseCardService;
    @Autowired
    private ScheduleRecordService scheduleRecordService;

    /**
     * 跳转到课程列表页面
     */
    @GetMapping("/x_course_list.do")
    public String memberCard() {
        return "course/x_course_list";
    }

    /**
     * 获取课程列表数据
     */
    @PostMapping("/courseList.do")
    @ResponseBody
    public R courseList() {
        List<CourseEntity> list = courseService.list(null);
        return new R().put("data", list);
    }

    /**
     * 跳转到课程添加页面
     */
    @GetMapping("/x_course_list_add.do")
    public String courseListHTML() {
        return "course/x_course_list_add";
    }

    /**
     * 添加课程
     */
    @PostMapping("/courseAdd.do")
    @ResponseBody
    public R courseAdd(@Valid CourseEntity courseEntity, BindingResult bindingResult, String cardListStr) {
        if (bindingResult.hasErrors()) {
            HashMap<String, String> errorMap = new HashMap<>();
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            return R.error(400, "非法参数").put("errorMap", errorMap);
        }
        List<String> list = new ArrayList<>();
        if (cardListStr != null) {
            list = Arrays.asList(cardListStr.split(","));
        }
        if (courseService.save(courseEntity)) {
            for (String s : list) {
                CourseCardEntity courseCardEntity = new CourseCardEntity();
                courseCardEntity.setCardId(Long.valueOf(s));
                courseCardEntity.setCourseId(courseEntity.getId());
                courseCardService.save(courseCardEntity);
            }
            return R.ok("添加成功").put("data", courseEntity);
        } else {
            return R.error("添加失败,请重试");
        }
    }

    /**
     * 跳转到课程编辑页面
     */
    @GetMapping("/x_course_list_edit.do")
    public String courseListEdit(Integer id, Model model) {
        CourseEntity courseEntity = courseService.getById(id);
        List<CourseCardEntity> courseCardEntityList = courseCardService.list(new QueryWrapper<CourseCardEntity>().eq("course_id", id));
        List<Long> cardIds = new ArrayList<>();
        for (CourseCardEntity courseCardEntity : courseCardEntityList) {
            cardIds.add(courseCardEntity.getCardId());
        }
        model.addAttribute("cardCarry", cardIds);
        model.addAttribute("courseInfo", courseEntity);
        return "course/x_course_list_edit";
    }

    /**
     * 编辑课程
     */
    @PostMapping("/courseEdit.do")
    @ResponseBody
    public R courseEdit(@Valid CourseEntity courseEntity, String cardListStr, @RequestParam("limitAgeRadio") String limitAgeRadio, @RequestParam("limitCountsRadio") String limitCountsRadio) {
        System.out.println("课程信息：" + courseEntity);
        System.out.println(limitAgeRadio);
        if (limitCountsRadio.equals("无限制")) {
            courseEntity.setLimitCounts("无限制");
        }
        if (limitAgeRadio.equals("无限制")) {
            courseEntity.setLimitAge("无限制");
        }
        //先删除与课程相关的cardId后添加
        List<CourseCardEntity> courseCardEntityList = courseCardService.list(new QueryWrapper<CourseCardEntity>().eq("course_id", courseEntity.getId()));
        List<String> cardIds = new ArrayList<>();
        for (CourseCardEntity courseCardEntity : courseCardEntityList) {
            cardIds.add(String.valueOf(courseCardEntity.getCourseId()));
        }
        courseCardService.remove(new QueryWrapper<CourseCardEntity>().eq("course_id", courseEntity.getId()));
        //接收前端传来的id
        if (cardListStr.contains("on")) {
            cardListStr = cardListStr.replace("on,", "");
        }

        List<String> list = Arrays.asList(cardListStr.split(","));
        for (String s : list) {
            CourseCardEntity courseCardEntity = new CourseCardEntity();
            courseCardEntity.setCardId(Long.valueOf(s));
            courseCardEntity.setCourseId(courseEntity.getId());
            courseCardService.save(courseCardEntity);
        }
        CourseEntity courseEntity1 = courseService.getById(courseEntity);
        BeanUtils.copyProperties(courseEntity, courseEntity1, IGNORE);
        if (courseService.updateById(courseEntity1)) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    /**
     * 课程搜索
     */
    @GetMapping("/toSearch.do")
    @ResponseBody
    public R toSearch() {
        List<CourseEntity> list = courseService.list(null);
        return R.ok().put("value", list);

    }

    /**
     * 排课
     */
    @PostMapping("/getOneCourse.do")
    @ResponseBody
    public R getOneCourse(Long id) {
        CourseEntity courseEntity = courseService.getById(id);
        CourseLimitVo courseLimitVo = new CourseLimitVo();
        courseLimitVo.setLimitSex(courseEntity.getLimitSex())
                .setDuration(courseEntity.getDuration())
                .setLimitAge(courseEntity.getLimitAge());
        return R.ok().put("data", courseLimitVo);
    }

    /**
     * 删除课程
     */
    @PostMapping("/deleteOne.do")
    @ResponseBody
    public R deleteOne(@RequestParam("id") Integer id) {
        int CourseCardCount = courseCardService.count(new QueryWrapper<CourseCardEntity>().eq("course_id", id));
        if (CourseCardCount > 0) {
            courseCardService.remove(new QueryWrapper<CourseCardEntity>().eq("course_id", id));
        }
        int scheduleCourseCount = scheduleRecordService.count(new QueryWrapper<ScheduleRecordEntity>().eq("course_id", id));
        if (scheduleCourseCount > 0) {
            return R.error("此课程已有排课记录，无法删除！");
        }
        boolean isRemoveCourse = courseService.removeById(id);
        if (isRemoveCourse) {
            return R.ok("删除成功!");
        } else {
            return R.error("删除失败!");
        }
    }
}
